package cn.puge.mertisfront.controller;


import cn.puge.commonutils.R;
import cn.puge.mertisfront.entity.TestOrder;
import cn.puge.mertisfront.service.TestOrderService;
import cn.puge.mertisfront.utils.HttpClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LIJW
 * @since 2020-12-29
 */
@CrossOrigin
@RestController
@RequestMapping("/testgkk/puge-info")
public class PugeInfoController {


    @Autowired
    private TestOrderService testOrderService;
    /**
     * 生成微信支付二维码
     * @param payId
     * @return
     */
    @GetMapping("/createNative/{payId}")
    public Map createNative(@PathVariable String payId) {

        QueryWrapper<TestOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no",payId);
        TestOrder one = testOrderService.getOne(queryWrapper);


        try {

            Map m = new HashMap();
            //1、设置支付参数
            m.put("appid", "wx84b3b2fe8beaa59a");
            m.put("mch_id", "1604549696");
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            m.put("body", one.getTestDes());
            m.put("out_trade_no", payId);
            m.put("total_fee", one.getPrice().multiply(new BigDecimal("100")).longValue()+"");
            m.put("spbill_create_ip", "127.0.0.1");
            m.put("notify_url", "http://localhost:8001/wxpay/paytest");
            m.put("trade_type", "NATIVE");

            //2、HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");

            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "pugelijianwei20190513pugelijianw"));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //4、封装返回结果集
            Map map = new HashMap<>();
            map.put("out_trade_no", payId);
            map.put("course_id", one.getTestpaydesId());
            map.put("total_fee", one.getPrice());
            map.put("result_code", resultMap.get("result_code"));
            map.put("code_url", resultMap.get("code_url"));

            //微信支付二维码2小时过期，可采取2小时未支付取消订单
            //redisTemplate.opsForValue().set(orderNo, map, 120, TimeUnit.MINUTES);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }

    }


    @GetMapping("/queryPayStatus/{orderNo}")
    public R queryPayStatus(@PathVariable String orderNo) {
        Map<String, String> resultMap = null;
        //调用查询接口
        try {
            //1、封装参数
            Map m = new HashMap<>();
            m.put("appid", "wx84b3b2fe8beaa59a");
            m.put("mch_id", "1604549696");
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2、设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "pugelijianwei20190513pugelijianw"));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            resultMap = WXPayUtil.xmlToMap(xml);
            //6、转成Map
            //7、返回
        } catch (Exception e) {
            e.printStackTrace();
        }


        if (resultMap == null) {//出错
            return R.error().message("支付出错");
        }
        if (resultMap.get("trade_state").equals("SUCCESS")) {//如果成功
            TestOrder testOrder = new TestOrder();
            testOrder.setStatus("1");
            QueryWrapper<TestOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_no",orderNo);
            //更改订单状态
            testOrderService.update(testOrder,queryWrapper);
            System.out.println("支付成功");
            return R.ok().message("支付成功");
        }

        return R.ok().code(25000).message("支付中");
    }



}

